package com.example.design.core;

import com.example.design.utils.FileUtils;

import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;

/**
 * 文件分发器核心逻辑
 */
public abstract class EnhancedFileProcessor<T extends Enum<T> & SyncFieldDefinition> {

    protected abstract List<ProcessorRegistration<T>> getProcessorRegistrations();

    public void processFiles(List<Path> files, FileProcessingContext<T> context) throws Exception {
        List<ProcessorRegistration<T>> regs = getProcessorRegistrations();

        for (Path file : files) {
            String fileName = file.getFileName().toString();
            String ext = FileUtils.getExtension(fileName);

            // 根据优先级选匹配处理器
            ProcessorRegistration<T> match = regs.stream()
                    .filter(r -> r.getMatcher().matches(file, fileName, ext))
                    .min(Comparator.comparingInt(ProcessorRegistration::getPriority))
                    .orElse(null);

            if (match != null) {
                try {
                    match.getProcessor().process(file, fileName, context);
                } catch (Exception e) {
                    context.addSystemError(fileName, "文件处理失败", e);
                }
            } else {
                context.addFileError(fileName, "未找到匹配的处理器");
            }
        }
    }
}
